package com.onemore.task.location;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.voovan.tools.log.Logger;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.response.handle.StringDataHandler;
import com.onemore.task.OneJdbc;
import com.onemore.task.QimenSign;
import com.onemore.task.model.ModelJsend;
import com.onemore.task.model.ModelJsendmx;
import com.onemore.task.model.ModelSpjhd;
import com.onemore.task.model.ModelSpjhdmx;
import com.onemore.task.model.ModelSpthd;

public class LocTaskSpjhd  extends LocTaskBase{
	public static void process(String DJBH,String stamp) throws SQLException, InterruptedException
	{	
		int ret=0;
		List<Map<String, Object>> listSpjhd = null; 
		List<Map<String, Object>> listSpjhdmx = null; 

		listSpjhd = OneJdbc.getSpjhd(DJBH);
		//等等此表同步完成
		Thread.sleep(10);
		listSpjhdmx = OneJdbc.getSpjhdmx(DJBH);
		if(listSpjhd != null && listSpjhd.size() > 0) {
			listSpjhd.get(0).put("items", listSpjhdmx);
			ret = LocTaskSpjhd.postHttpForSpjhdInsert(listSpjhd,listSpjhdmx);
			//if(ret == 0 || ret == 200) 
			{
//				ModelSpjhd.updateFlag(DJBH);
				//清除
				if(OneJdbc.deleteMtab(stamp)) {
				}
			}
		}else {
			Logger.error("未找到进货单数据");
			//清除
			OneJdbc.deleteMtab(stamp);
		}
	}
	/**
	 * 商品入库数据提交给SCM系统
	 * @param spjhd
	 * @return
	 * @deprecated insert into ONE_MTAB (KEY_VALUE,ACT_TYPE,TAB_NAME) values('JA6120320000003','SPJHD','insert');
	 */
	public static int postHttpForSpjhdInsert(JSONObject spjhd)
	{
		int ret=0;
		String url = "/test/R/RestHandle.ashx";//scm
		url += "?method=scm.160240.rkd.rk";
		url += "&timestamp="+df.format(new Date());
		url += "&format=json";
		url += "&app_key=scm.om.bs";
		url += "&v=2.0";
		url += "&sign_method=md5";
		url += "&customerId=onemore";
		String body = spjhd.toJSONString();
        QimenSign sign = new QimenSign();
        String md5 = sign.sign(url, body, secretKey);
		url += "&sign="+md5;
		outer:do {
			Logger.info("SCM发送进货单链接："+(host+url)+"\r\n Body:"+body);
			com.mzlion.easyokhttp.response.HttpResponse httpResponse = com.mzlion.easyokhttp.HttpClient.textBody(host+url)
                .text(body)
                .charset(charset)
                .execute();
	        String asString = httpResponse.custom(StringDataHandler.create(), false);
	        if(httpResponse.getHttpCode() == 200) {
	        	if(asString != null && asString != "") {
			        JSONParser parse =new JSONParser(asString);  //创建json解析器
			        JSONObject jsonObject= new JSONObject(parse.parseMap());
			        ret = jsonObject.getInteger("code");
			        /*if(jsonObject.getInteger("code") == 200) {
						Logger.info("成功同步一条进货数据");
			        	break outer;
			        }*/
	        	}else {
	        		ret = -450;
	        	}
	        }else {
	        	ret = -451;
	        }
	        if(ret == 200) {
				Logger.info("成功同步一条进货数据:"+asString);
	        }else
	        if(httpResponse.getHttpCode() != 200) {
	        	Logger.error("商品入库失败 http返回 code = "+httpResponse.getHttpCode()+" 错误消息："+httpResponse.getErrorMessage());
	        }else
	        if(ret != 200) {
	        	Logger.error("商品入库服务器返回失败 报文："+asString+" 错误计数："+"\r\n请求报文："+body);
	        }
		}while(false);
		return ret;
	}

	public static int postHttpForSpjhdInsert(List<Map<String,Object>> listSpthd, List<Map<String,Object>> listSpthdmx) throws SQLException
	{
		JSONObject jsonObject = readyDataToSPJHD(listSpthd, listSpthdmx);
		if(jsonObject == null) {
			return 0;
		}else
			return postHttpForSpjhdInsert(jsonObject);
	}
	/**
     * 将进货单的数据库查询到的数据转化为报文json格式
     * @param json
     * @return
	 * @throws SQLException 
     */
	public static JSONObject readyDataToSPJHD(List<Map<String,Object>> listSpjhd, List<Map<String,Object>> listSpjhdmx) throws SQLException
	{
		int itemCnt = 0;
		Map<String, JSONArray> skusmap = new HashMap<String,JSONArray>();
		Map<String,Object> spjhdMap = listSpjhd.get(0);
		JSONObject scmJsonObject = new JSONObject();
		String jsendBh = (String)spjhdMap.get("LXDJ");//通知单单号 原BYZD3
		if(jsendBh == null) {
			Logger.info("数据库对应的进货通知单号为空，此条数据无效，可能不是SCM的数据，所以无法发送。单据编号:"+spjhdMap.get("DJBH"));
			return null;
		}
		if(!ModelJsendmx.isExist(jsendBh)) {
			Logger.error("进货通知单对应的明细表没有数据，发送过去也没有意义，所以本系统将自动此数据自动忽然。单据编号:"+spjhdMap.get("DJBH")+" 通知单单号:"+jsendBh);
			return null;
		}
		scmJsonObject.put("sdh", jsendBh);//SCM入库通知单单号
		scmJsonObject.put("wdh", spjhdMap.get("DJBH"));//WMS入库单单号
		scmJsonObject.put("sm", spjhdMap.get("BZ"));//备注
		String ywy = null;
		if(spjhdMap.containsKey("JZR"))
			ywy = (String)spjhdMap.get("JZR");
		if(ywy == null)ywy = "undefined";
		scmJsonObject.put("_su", ywy);//维护用户名
		scmJsonObject.put("_st", df.format(new Date()));//维护用户名
		JSONArray itemsArray = new JSONArray();
		
		for(int i=0;i<listSpjhdmx.size();i++) {
			Map<String,Object> spjhdmxMap = listSpjhdmx.get(i);
			String gg1dm = (String)spjhdmxMap.get("GG1DM");
			String chima = (String)spjhdmxMap.get("GG2DM");
			String SPDM = (String)spjhdmxMap.get("SPDM");
			String PKID = null;
			try {
				PKID = ModelJsendmx.getPkidFromJsendmx(jsendBh,gg1dm,SPDM);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				Logger.error(e);
				continue;
			}
			if(PKID == null) {
				Logger.warn("在同步商品进货单时，获取到的商品的PKID为空,通知单号（jsendBh）："+jsendBh+" 颜色代码："+gg1dm+" 商品代码："+SPDM);
				continue;
			}
			JSONObject skuObject = new JSONObject();
			skuObject.put("sku", spjhdmxMap.get("SPDM")+gg1dm+chima);
			skuObject.put("qty", spjhdmxMap.get("SL"));//入库数	
			JSONArray tmpAry = skusmap.get(PKID);
			if(tmpAry == null) {
				tmpAry = new JSONArray();
				skusmap.put(PKID,tmpAry);
			}
			tmpAry.add(skuObject);
			itemCnt++;
		}
		if(itemCnt == 0) {
			Logger.error("进货单的商品信息与SCM通知单的商品信息不能对应，此数据自动被忽略,JSON:"+scmJsonObject.toJSONString());
			return null;
		}
		for (Map.Entry<String, JSONArray> entry : skusmap.entrySet()) {
			JSONObject itemObject = new JSONObject();
			itemObject.put("pkid", entry.getKey());
			itemObject.put("skus", entry.getValue());
			itemsArray.add(itemObject);
		}  
		scmJsonObject.put("items", itemsArray);
		return scmJsonObject;
	}
}
